package com.xzp.blog.controller;

import com.xzp.blog.controller.base.BaseController;
import com.xzp.blog.entity.Article;
import com.xzp.blog.entity.dto.form.ArticleSearchForm;
import com.xzp.blog.entity.vo.PostView;
import com.xzp.blog.entity.vo.TagView;
import com.xzp.blog.service.IArticleService;
import com.xzp.blog.service.IPostsService;
import com.xzp.blog.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.xzp.blog.consts.ViewConsts.*;

/**
 * 博客控制器
 */
@Controller
public class PostContoller extends BaseController {

    @Autowired
    private IPostsService postsService;

    @Autowired
    private ITagService tagService;

    @Autowired
    private IArticleService articleService;
    /**
     * 博客列表页
     * 视图模型：
     * 1.博客列表（文章标题/内容简介/发布时间）
     * 2.标签（tagId/文章总数）---------  响应点击标签,得到相关文章
     */
    @GetMapping("/post")
    public String postList(HttpServletRequest request, Model model,Integer tagId) throws Exception {
        List<PostView> postViewList = null;

        if (tagId != null){
            postViewList = postsService.getPostListByTagId(tagId);
        }else {
            postViewList = postsService.getPostList();
        }

        List<TagView> tagViewList = tagService.getAllTagView();

        addModelAtt(model,VIEW_TAGLIST,tagViewList);  //将所有的list添加到model中来
        addModelAtt(model,VIEW_POSTLIST,postViewList);

        return "posts";

    }

    @GetMapping("/blog/{id}")
    public String frontBlogView(HttpServletRequest request, Model model, @PathVariable Integer id) throws Exception {
//        Article article = .......
        Article article = articleService.getArticleById(id);
        PostView postView = new PostView(article);
        addModelAtt(model,VIEW_ARTICLE,postView);
        addModelAtt(model,VIEW_TITLE,article.getTitle());

        return "article";
    }

    @GetMapping("/postsearch")
    public String frontBlogSearch(HttpServletRequest request, Model model, ArticleSearchForm form) throws Exception {
        List<PostView> postViewList = postsService.getPostListByArticleCondition(form);
        addModelAtt(model,VIEW_POSTLIST,postViewList);

        List<TagView> tagViewList = tagService.getAllTagView();
        addModelAtt(model,VIEW_TAGLIST,tagViewList);

        return "posts";
    }



}
